package com.yizhuoyan.his.web.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebFilter(urlPatterns = "*.html", dispatcherTypes = DispatcherType.REQUEST)
public class HTMLViewForwardFilter implements Filter {
    @Autowired
    FreeMarkerViewResolver freeMarkerViewResolver;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        final String requestURI = req.getRequestURI();
        String viewName = requestURI.substring(0, requestURI.lastIndexOf('.'));
        try {
            View view = freeMarkerViewResolver.resolveViewName(viewName + "/view", req.getLocale());
            if (view != null) {
                Map<String,Object> model=new HashMap<>(2,1);
                model.put("baseHref",viewName+"/");
                view.render(model, req, resp);
            } else {
                servletRequest.getRequestDispatcher(viewName + "/view.html").forward(servletRequest, servletResponse);
            }
        } catch (Exception e) {
            resp.sendError(500);
            e.printStackTrace();
        }


    }
}
